using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Bom;
using WPF_MVVM_Test.MVVM_Model.Bom.Bom;

namespace WPF_MVVM_Test.Services.Bom
{
    /// <summary>
    /// BOM服务类
    /// </summary>
    public class BomService
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl = "http://8.140.242.140:8888/api/Bom";

        public BomService()
        {
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
        }

        /// <summary>
        /// 新增BOM
        /// </summary>
        /// <param name="bomRequest">BOM新增请求数据</param>
        /// <returns></returns>
        public async Task<BomAddResponseModel> AddBomAsync(BomAddRequestModel bomRequest)
        {
            try
            {
                var url = $"{_baseUrl}/add";

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 开始新增BOM，URL: {url}");

                // 序列化请求数据
                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented = true
                };

                var jsonString = JsonSerializer.Serialize(bomRequest, options);
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 请求数据: {jsonString}");

                var content = new StringContent(jsonString, Encoding.UTF8, "application/json");

                // 发送POST请求
                var response = await _httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] BOM新增API响应: {responseContent}");

                    var deserializeOptions = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };

                    var result = JsonSerializer.Deserialize<BomAddResponseModel>(responseContent, deserializeOptions);

                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] BOM新增成功，响应解析完成");
                        return result;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] BOM新增响应解析失败");
                        return new BomAddResponseModel
                        {
                            IsSuc = false,
                            Code = 500,
                            Msg = "响应数据解析失败"
                        };
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] BOM新增API请求失败，状态码: {response.StatusCode}，错误内容: {errorContent}");

                    return new BomAddResponseModel
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.StatusCode} - {errorContent}"
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] BOM新增API请求异常: {ex.Message}");
                return new BomAddResponseModel
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }



        /// <summary>
        /// 获取分页BOM列表
        /// </summary>
        /// <param name="queryParams">查询参数</param>
        /// <returns>BOM分页数据</returns>
        public async Task<BomPagedData> GetBomPagedAsync(BomQueryParams queryParams)
        {
            try
            {
                // 构建查询URL
                var url = $"{_baseUrl}/paged?pageIndex={queryParams.PageIndex}&pageSize={queryParams.PageSize}";

                if (!string.IsNullOrEmpty(queryParams.ProductName))
                {
                    url += $"&productName={Uri.EscapeDataString(queryParams.ProductName)}";
                }

                if (!string.IsNullOrEmpty(queryParams.BomNumber))
                {
                    url += $"&bomNumber={Uri.EscapeDataString(queryParams.BomNumber)}";
                }


                // 发送GET请求
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();

                    // 配置JSON序列化选项
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                        UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
                    };

                    var apiResponse = JsonSerializer.Deserialize<BomApiResponse>(jsonString, options);

                    if (apiResponse?.IsSuc == true && apiResponse.Data != null)
                    {
                        return apiResponse.Data;
                    }
                    else
                    {
                        throw new Exception($"API返回错误: {apiResponse?.Msg ?? "未知错误"}");
                    }
                }
                else
                {
                    throw new Exception($"HTTP请求失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"获取BOM数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}